package com.water.app.Controller.account;


import com.water.app.*;
import com.water.app.interfaces.account.EmailService;
import com.water.app.interfaces.account.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/register")
public class RegisterController {
    private static final Logger log= LoggerFactory.getLogger(RegisterController.class);
    @Autowired
    RegisterService registerService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    EmailService emailService;

    @PostMapping("/c1")
    public Result register1(@RequestBody User user) {
        log.info("user:{}",user);
        if (registerService.AccountIsExist(user.getUsername())) {
            log.info("用户名已存在");
            return Result.error("用户名已存在");
        }

        if (user.getPassword().length()<6){
            log.info("密码有误");
            return Result.error("密码不能少于6位");
        }


        if (!registerService.verifyEmail(user.getEmail())){
            log.info("qq邮箱已存在");
            return Result.error("qq邮箱已存在");
        }

//        if (registerService.verifyEmail(user.getEmail())){
//            log.info("qq邮箱号不符合规范");
//            return Result.error("qq邮箱号不符合规范");
//        }

        int i = emailService.sendEmail(user.getEmail());
        stringRedisTemplate.opsForValue().set(Constant.REGISTER+user.getUsername(),
                String.valueOf(i),5, TimeUnit.MINUTES);
        Random random = new Random();
        random.nextInt();
        return Result.success(i);
    }


    @PostMapping("/c2")
    public Result Register(@RequestBody User user){
        String s = stringRedisTemplate.opsForValue().get(Constant.REGISTER + user.getUsername());
        log.info("user:{}",user);
            if (s==null||s.isEmpty()){
              return Result.error("验证码已过期");
            }

            if (!s.equalsIgnoreCase(String.valueOf(user.getCaptcha()))){
                log.info("验证码错误");
                return Result.error("验证码错误");
            }
            user.setMoney(0);



            if(registerService.registerUser(user)) {
                log.info("注册成功");
                return Result.success("注册成功");
            }
            log.info("注册失败");
            return Result.error("注册失败");
    }

}


